package view.controller;

import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.Initializable;


import javafx.fxml.FXML;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.*;
import javafx.stage.Stage;
import utils.Connect;
import utils.Group;
import utils.User;
import view.MainWindow;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
/**
 * @author
 */
public class CreateGroupViewController implements Initializable {
    @FXML
    private TextField inputGroupNameIdentity;

    @FXML
    private Button createGroupButton;

    @FXML
    private TextField groupUrl;
    @FXML
    private ImageView imageView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    @FXML
    public void setMouse(DragEvent dragEvent) {
        dragEvent.acceptTransferModes(TransferMode.ANY);
    }

    @FXML
    public void loadImage(DragEvent dragEvent) {
        Dragboard dragboard = dragEvent.getDragboard();
        if (dragboard.hasFiles()) {
            String path = dragboard.getFiles().get(0).getAbsolutePath();
            path = "file:" + path;
            groupUrl.setText(path);
            this.getImage(null);
        }
    }
    @FXML
    private void getImage(MouseEvent event) {
        Image image = new Image(groupUrl.getText());
        imageView.setImage(image);
    }


    @FXML
    private void createGroup(MouseEvent event) throws IOException {
        WritableImage image = imageView.snapshot(new SnapshotParameters(), null);
        try {
            ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", new File("photo/temp/temp.png"));
        } catch (IOException ex) {
        }
        ArrayList<User> list=new ArrayList<>();
        list.add(MainWindow.getMainWindow().getUser());
        Group group=new Group(null,inputGroupNameIdentity.getText(),list);
        group.setHostAccount(MainWindow.getMainWindow().getUser().getAccount());
        Connect.getConnect().createGroup(MainWindow.getMainWindow().getUser(),group);

        Alert alert = new Alert(Alert.AlertType.INFORMATION, "创建成功", new ButtonType("确认", ButtonBar.ButtonData.YES));
        alert.setTitle("提示");
        alert.show();

        Stage stage=(Stage) createGroupButton.getScene().getWindow();
        stage.close();
    }

    @FXML
    public void createKeyPressed(KeyEvent event) throws IOException {
        if (event.getCode() == KeyCode.ENTER) {
            this.createGroup(null);
        }
        //this.alert(new ActionEvent());
    }
}
